<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Cache;
use app\index\model\Conf as Confs;
use think\Config;
use app\admin\model\Kami as km;

// 应用公共文件
/*
 * $string 1 数字 2英文 3数字+英文
 * $num     加密长度  默认6位
 *
 */
function RandPsw($string = '1', $leng = '6')
{
    switch ($string) {
        case "1":
            $string = '0123456789';
            return AllPsw($string, $leng);
            break;
        case  '2':
            $string = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOASDFGHJKLZXCVBNM';
            return AllPsw($string, $leng);
            break;
        case  '3':
            $string = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOASDFGHJKLZXCVBNM0123456789';
            return AllPsw($string, $leng);
            break;
    }
}

function AllPsw($str, $leng)
{
    $psw = "";
    for ($i = 0; $i < $leng; $i++) {
        $psw .= substr($str, mt_rand(0, strlen($str) - 1), 1);
    }
    return $psw;
}

function DateTime($time)
{
    return date('Y-m-d H:i:s', $time);
}

//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url, $post = '', $cookie = '', $returnCookie = 0)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //去ssl认证
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, '0');
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, '0');
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie'] = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

function getDyIndex($info)
{
//    dump($info);
    $data = [];
    $vname = '#<spanclass=\'s1\'>(.*?)</span>#';//取出电影的名字
    $fname = '#<spanclass=\'s2\'>(.*?)</span>#';//取出电影的评分
    $nname = '#<spanclass=\'w-newfigure-hint\'>(.*?)</span>#';//取出电影的年份
    $vimg = '#<imgsrc=\'(.*?)\'data-src=\'(.*?)\'#';//取出电影的剧照
    $va = '#<ahref=\'(.*?)\'class=\'js-link\'>#';//取出电影的链接
    $zy = '#<pclass=\'w-newfigure-desc\'>(.*?)</p>#';//取出电影的摘要
    preg_match_all($vname, $info, $index_vname);

    preg_match_all($fname, $info, $index_fname);
    preg_match_all($nname, $info, $index_nname);
    preg_match_all($vimg, $info, $index_vimg);
    preg_match_all($va, $info, $index_va);
    preg_match_all($zy, $info, $index_zy);
    $data = [
        'vname' => $index_vname,
        'fname' => $index_fname,
        'nname' => $index_nname,
        'vimg' => $index_vimg,
        'va' => $index_va,
        'zy' => $index_zy,
    ];

    return $data;
}

/**
 * @param $info             采集地址
 * @param bool $tpye 类型  如：电影  电视剧等
 * @return array|bool
 */
function getDyData($info, $tpye = '')
{
    if ($tpye == 'dy') {
        $div = '#<divclass="g-wrapg-clearmod2">(.*?)<divclass="content"><ulclass="w-newfigure-listg-clear"><li(.*?)class=\'w-newfigurew-newfigure-180x299\'>(.*?)</li></ul></div>#';

        preg_match_all($div, $info, $two);
        if (isset($two[3])) {
            return getDyIndex($two[3][0]);
        }
        return false;
    }
    if ($tpye == 'dsj') {
        $div = '#<divclass="content-wrapg-clear">(.*?)<divclass="content"><ulclass="listw-newfigure-listg-clear"><li(.*?)class=\'w-newfigurew-newfigure-180x299\'>(.*?)</li></ul></div>#';
        preg_match_all($div, $info, $dsj);
        return getDyIndex($dsj[3][0]);


    }

    $pages = '#<ahref=\'(.*?)\'target=\'_self\'>(.*?)</a>#';
    $vname = '#<spanclass="s1">(.*?)</span>#';//取出电影的名字
    $fname = '#<spanclass="s2">(.*?)</span>#';//取出电影的评分
    $nname = '#<spanclass="hint">(.*?)</span>#';//取出电影的年份
    $vlist = '#<aclass="js-tongjic"href="(.*?)">#';//取出电影的详情列表
    $vstar = '#<pclass="star">(.*?)</p>#';//取出电影的主演
    $vimg = '#<divclass="coverg-playicon"[^"]*src="(.*?)">#';
    $bflist = '#<adata-daochu(.*?)href="(.*?)"class="js-site-btnbtnbtn-play"></a>#';
    $data = [];
    preg_match_all($pages, $info, $page);
    preg_match_all($vname, $info, $namearr);
    preg_match_all($vlist, $info, $listarr);
    preg_match_all($vstar, $info, $stararr);
    preg_match_all($vimg, $info, $imgarr);
    preg_match_all($fname, $info, $fnamearr);
    preg_match_all($nname, $info, $nnamearr);
    $data = [
        'page' => $page,
        'namearr' => $namearr,
        'listarr' => $listarr,
        'stararr' => $stararr,
        'imgarr' => $imgarr,
        'fnamearr' => $fnamearr,
        'nnamearr' => $nnamearr,
    ];

    return $data;

}

//新开发功能后在来做首页排版问题
function getIndexData($info)
{

    /**
     * 热点聚焦
     */
    $top1 = '';
}

/**
 * getPayData   播放页面
 */
function getPayData($info)
{

    $player = base64_decode($info);
    $tvinfo = DeleteHtml(curl_request($player));
    //电影a
    //<divclass="num-tab-maing-clearjs-tab"><adata-num="1"data-daochu="to=qq"href="http://v.qq.com/x/cover/vxz0cpf5fawnghw/u0026nf7g8r.html?ptag=360kan.tv.free">1</a>
    $dy_href = '#<divclass="top-list-btnsg-clear"id=\'js-site-wrap\'><adata-daochu="(.*?)"href="(.*?)"class="js-site-btnbtnbtn-play"></a>#';

    $dy_title = '#<h1>(.*?)</h1>#';
    $dy_tag = '#<pclass="tag">(.*?)</p>#';
    $dy_briefing = '#<pclass="item-descjs-open-wrap">(.*?)</p>#';


    //电影播放地址
    preg_match_all($dy_href, $tvinfo, $pay_url);
//    dump($tvinfo);die;
//    dump($pay_url);die;
    if ($pay_url[2] == false) {
        $ds_href = '#<divclass="num-tab-maing-clearjs-tab"*(style="display:none;")?><adata-num="(.*?)"data-daochu="(.*?)"href="(.*?)"></div>#';
        //第一次匹配电视剧播放地址
        preg_match_all($ds_href, $tvinfo, $pay_s_url);
//        return $pay_s_url;

        $init = implode('', $pay_s_url[0]);
        //第二次匹配播放地址
        $ds_a = '#<adata-num="(.*?)"data-daochu="to=(.*?)"href="(.*?)"#';

        preg_match_all($ds_a, $init, $tvarr1);
//return $tvarr1;
        $data['pay_url'] = $tvarr1['3'];  //播放地址

        $data['pay_to'] = $tvarr1['2'];   //是否预告

    } else {
        $data['pay_url'] = $pay_url[2][0];  //播放地址

    }

    //电影标题
    preg_match_all($dy_title, $tvinfo, $pay_title);
    //电影标签
    preg_match_all($dy_tag, $tvinfo, $pay_tag);
    //电影介绍
    preg_match_all($dy_briefing, $tvinfo, $pay_briefing);

    $data['pay_title'] = $pay_title[1][0];
    $data['pay_tag'] = $pay_tag[1][0];
    $data['pay_briefing'] = $pay_briefing[1][0];

    return $data;
}

/**
 *
 */
function getSeacher($info)
{
    $url = config('sokanurl') . '/' . 'index.php?kw=' . input('key');
    $seach = curl_request($url);
    $seacher_img = '#<img src="(.*?)" alt="(.*?)" \/>[\s\S]+?</a>\n</div>#';
    $seacher_a = '#a href="(.*?)" class="g-playicon js-playicon"#';
    $seacher_type = '#<span class="playtype">(.*?)</span>#';
    $seacher_title = '#js-playicon" title="(.*?)"\s*data#';
    $seacher_get = '#(<b>(.*?)</b><span>(.*?)</span></li></ul>)?<ul class="index-(.*?)-ul g-clear">(\n\s*)?<li>(\n\s*)?<b>类型：</b>(\n\s*)?<span>(.*?)</span>#';


    preg_match_all($seacher_img, $seach, $img);      //电影图片
    preg_match_all($seacher_a, $seach, $a);          //电影网址
    preg_match_all($seacher_title, $seach, $title);          //电影标题
    preg_match_all($seacher_type, $seach, $type);          //电影标题
    preg_match_all($seacher_get, $seach, $get);          //电影更新


    $data = [
        's_title' => $title[1],
        's_a' => $a[1],
        's_img' => $img[1],
        's_type' => $type[1],
        's_get' => $get[3],

    ];
    return $data;
}


/**
 * @param $str    curl url
 * @return string  去空、行 并将替换为空
 */
function DeleteHtml($str)
{
    $str = trim($str); //清除字符串两边的空格
    $str = preg_replace("/\t/", "", $str); //使用正则表达式替换内容，如：空格，换行，并将替换为空。
    $str = preg_replace("/\r\n/", "", $str);
    $str = preg_replace("/\r/", "", $str);
    $str = preg_replace("/\n/", "", $str);
    $str = preg_replace("/ /", "", $str);
    $str = preg_replace("/  /", "", $str);  //匹配html中的空格
    return trim($str); //返回字符串
}

function insertAt($items, $index, $value)
{
    array_splice($items, $index, $value);

    return $items;
}

//电影显示数
/**
 * @param $data       数组
 * @param $type       数组值
 * @param $typeNum    数组值下的第几个数组
 * @param $num        需要数量 默认8个
 */
function DataNum($data, $type, $typeNum = 0, $num = 8)
{

    if (!isset($data)) {
        return false;
    }
    $array = [];
    for ($i = 0; $i <= ($num - 1); $i++) {

        $array[$type][$typeNum][] = $data[$type][$typeNum][$i];
    }
//    dump(array_merge($data, $array));
    return array_merge($data, $array);
}

/**
 * @param $table        数据表名
 * @return string       返回获取数据库+数据表名
 */
function GetConf($table)
{
    return config('database.prefix') . $table;
}

function GetCL($data = '', $type = '')
{
    if ($type == true || $data == true) {
        return $data[$type];
    }

}

function GetConfDate($type = '')
{

    $data = db('Conf')->find();
    return $data[$type];
}

/**
 * @param $w        样式宽
 * @return string
 */
function InputStyle($w)
{

    return "style=" . "width:" . $w . 'px';
}

/**
 * @param int $length 卡密长度
 * @param int $type 卡密数组
 * @return string
 */
function randCode($length = 32, $type = 0, $kami = '')
{

    $arr = array(1 => "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz" . $kami);
    if ($type == 0) {
        array_pop($arr);
        $string = implode("", $arr);
    } elseif ($type == "-1") {
        $string = implode("", $arr);
    } else {
        $string = $arr[$type];
    }
    $count = strlen($string) - 1;
    $code = '';
    for ($i = 0; $i < $length; $i++) {
        $code .= $string[rand(0, $count)];
    }
    return $code;
}

/**
 * @param $d_name      卡密id
 * @return mixed       返回卡密类别名称
 */
function type_name($d_name)
{
    $arr = km::daili_type('f', $d_name);
    Cache::store('redis')->set('typename', $arr);
    return Cache::get('typename')['d_name'];
}

function getAdTime($ad_time_type)
{
    if ($ad_time_type == 1) {
        return '不限时间';
    }
    return '限时标记';
}

/**
 * @param $id       id
 * @return mixed
 */
function user_name($id)
{
    $user = db('user')->where('id', 'in', $id)->find();
    return $user['u_user'];

}

function Cfg()
{
    $ConfList = Confs::where('id', 'in', '1')->find();
    Cache::store('redis')->set('Conf', $ConfList);
    Config::set('Conf', Cache::get('Conf'));
    return config('Conf');
}

/**
 * @param string $id 广告ID
 * @return array|false|PDOStatement|string|\think\Model
 */
function AdList($id = '')
{

    $where = 'id = ' . $id . ' and ad_status = 1';

    return db('ad')->where($where)->find();
}

/** AdList方法后期废弃
 * @param string $id 广告ID
 * @param string $type 广告类型  img 图片广告 text 代码广告 title 文字广告
 * ######  缓存默认12个小时更新一次
 */
function getAds($id = '', $type = '', $typeId = '', $s = '12')
{
    $where = '1=1 and ad_status = 1 ';
    if ($id) {
        $where .= ' and id = ' . $id;
        $adId = db('ad')->where($where)->Cache(true, 60 * 60 * '"' . $s . '"')->find();
        switch ($type) {
            case 'img':
                echo "<a href=" . $adId['ad_img_a'] . " target=\"_blank\"><img src=" . $adId['ad_img'] . " width=\"" . $adId['ad_img_w'] . "\" height=\"" . $adId['ad_img_h'] . "\" /></a>";
                break;
        }
    }
    if ($typeId) {
        $where .= ' and ad_type = ' . $typeId;
        $array = db('ad')->where($where)->Cache(true, 60 * 60 * '"' . $s . '"')->select();
        switch ($type) {
            case 'img':
                foreach($array as $k=>$y){
                    echo "<div>";
                    echo "<a href=" . $y['ad_img_a'] . " target=\"_blank\"><img src=" . $y['ad_img'] . " width=\"" . $y['ad_img_w'] . "\" height=\"" . $y['ad_img_h'] . "\" /></a>";
                    echo "</div>";
                }

                break;
        }
    }

}